package com.pay.util;

import com.pay.pro.TextMessage;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/6/3.
 */
public class MessageUtil {

    public static String MESSAGE_TEXT     ="text";
    public static String MESSAGE_IMAGE    ="image";
    public static String MESSAGE_VIDEO    ="video";
    public static String MESSAGE_VOICE    ="voice";
    public static String MESSAGE_LOCATION ="location";
    public static String MESSAGE_LINK     ="link";
    public static String MESSAGE_EVENT    ="event";
    public static String EVENT_SUBSCRIBE  = "subscribe";
    public static String EVENT_CLICK      ="CLICK";
    public static String EVENT_VIEW       ="VIEW";
    /**
     * xml转map
     * @param request
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    public static Map<String,String> xmlToMap(HttpServletRequest request)
            throws IOException,DocumentException{
        Map<String,String> map  = new HashMap<String,String>();
        SAXReader reader        = new SAXReader();
        InputStream inputStream = request.getInputStream(); //获取输入流
        Document document       = reader.read(inputStream);
        Element root            = document.getRootElement();
        List<Element> list      = root.elements();

        for(Element e: list){
            map.put(e.getName(),e.getText());
        }
        inputStream.close();
        return map;
    }

    /**
     * 将文本消息转化成xml
     * @param msg
     * @return
     */
    public static String  MessageToXML(TextMessage msg){
        XStream xs =new XStream(new DomDriver()); //标注 不是new XStream() 而是new XStream(new DomDriver())
        xs.alias("xml",msg.getClass());
        return xs.toXML(msg);
    }

    /**
     * 信息菜单
     * @return
     */
    public static String menuText(){
        StringBuffer sb = new StringBuffer();
        sb.append("欢迎来到公众测试号！！！\n");
        sb.append("输入1,获取你的openid\n");
        sb.append("输入2,获取公众号的公众id\n");
        sb.append("输入？,提取菜单\n");
        return sb.toString();
    }

    /**
     * 拼接文本消息
     */
    public static String InitText(String fromUserName,String toUserName,String content){
        TextMessage textmsg = new TextMessage();
        textmsg.setToUserName(fromUserName);
        textmsg.setFromUserName(toUserName);
        textmsg.setMsgType("Text");
        textmsg.setCreateTime(String.valueOf(new Date().getTime()));
        textmsg.setContent("您发送的消息是:" + content);
        return MessageUtil.MessageToXML(textmsg);
    }
}
